package com.android.graffiti;

import android.content.Context;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.PorterDuff.Mode;
import android.graphics.Rect;
import android.util.TypedValue;

/**
 * 马赛克工具类(图片)
 */
public class MosaicUtils {

	private int mImageWidth;
	private int mImageHeight;
	
	private int GRID_WIDTH = 8;
	
	
	/**
	 * 九共格距离
	 */
	private int mGridWidth;
	
	
	/**
	 * 原图
	 */
	private Bitmap bmBaseLayer;
	
	private Context mContext;
	
	public MosaicUtils(Context context) {
		this.mContext = context;
	}
	
	
	private void initParameters(Bitmap srcBitmap) {		
		if (bmBaseLayer != null && !bmBaseLayer.isRecycled() && bmBaseLayer != srcBitmap) {
			bmBaseLayer.recycle();
		}
		
		bmBaseLayer = srcBitmap;
		mImageWidth = srcBitmap.getWidth();
		mImageHeight = srcBitmap.getHeight();
		
		mGridWidth = dp2px(GRID_WIDTH);
		//mGridWidth = this.GRID_WIDTH;
	}
	
	Canvas canvas;
	
	/**
	 * 返回默认马赛克
	 * @param srcBitmap
	 * @return
	 */
	public Bitmap getMosaicImage(Bitmap srcBitmap) {
		
		initParameters(srcBitmap);
		
		if (mImageWidth <= 0 || mImageHeight <= 0) {
			return null;
		}

		Bitmap bitmap = Bitmap.createBitmap(mImageWidth, mImageHeight,
				Config.ARGB_8888);
		canvas = new Canvas(bitmap);

		int horCount = (int) Math.ceil(mImageWidth / (float) mGridWidth);
		int verCount = (int) Math.ceil(mImageHeight / (float) mGridWidth);

		
		
		Paint paint = new Paint();
		paint.setAntiAlias(true);

		for (int horIndex = 0; horIndex < horCount; ++horIndex) {
			for (int verIndex = 0; verIndex < verCount; ++verIndex) {
				
				int left = mGridWidth * horIndex;
				int top = mGridWidth * verIndex;
				int right = left + mGridWidth;
				if (right > mImageWidth) {
					right = mImageWidth;
				}
				int bottom = top + mGridWidth;
				if (bottom > mImageHeight) {
					bottom = mImageHeight;
				}

				Rect rect = new Rect(left, top, right, bottom);
				
				
				//默认马赛克
				int color = bmBaseLayer.getPixel(left, top);
				paint.setColor(color);
				canvas.drawRect(rect, paint);
				
			}
		}
		canvas.save();
		return bitmap;
	}
	
	public void reset() {
		if (canvas != null) {
			canvas.drawColor(Color.TRANSPARENT, Mode.SRC);
		}
	}
	
	private int dp2px(int dip) {
		Resources resources = mContext.getResources();
		int px = Math.round(TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,dip, resources.getDisplayMetrics()));
		return px;
	}
	
}